package fr.pascal.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 2795043002485412720L;

	private final String DATA = "data";
	private String filePath;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		File file;
		response.setContentType("text/html");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator<FileItem> i = fileItems.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					String fileName = fi.getName();
					file = new File(filePath + File.separator + fileName.substring(fileName .lastIndexOf("\\") + 1));
					fi.write(file);

					// pour tester le contenu du fichier ligne par ligne
					System.out.println(file.getAbsolutePath());
					Scanner sc = new Scanner(new BufferedReader(new FileReader(file)));
					while (sc.hasNextLine()) {
						String ligne = sc.nextLine();
						System.out.println(ligne);
					}
					sc.close();
					// fin du test
				}
			}
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}

	@Override
	public void init() throws ServletException {
		filePath = getServletContext().getRealPath("/") + DATA;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdir();
		}
	}
}
